<script setup>
import {computed, ref, watch} from "vue";
import requestUtil from "@/utils/request";
import {ElMessage} from "element-plus";

const TableData = ref([])

const TreeData = ref([])
const props = defineProps({
  id: {
    type: Number,
    default: -1,
    required: true
  },
  dialogTitle: {
    type: String,
    default: '',
    required: true
  },
  dialogVisible: {
    type: Boolean,
    default: false,
    required: true
  },
  tableData: {
    type: Array,
    default: () => [],
    required: true
  },
})

const form = ref({
  id: -1,
  name: '',
  parent_id: 0,
})

const rules = ref({
      parent_id: [
        {required: true, message: '请选择上级分组'}
      ],
      name: [
        {required: true, message: '分组名称不能为空', trigger: 'blur'}
      ]
    }
)

const formRef = ref(null)

const initFormData = async (id) => {
  const res = await requestUtil.get('host/group/action?id=' + id)
  form.value = res.data.msg
}
const initGroupTreeData = () => {
  for (let i = 0; i < TreeData.value.length; i++) {
    const item = TreeData.value[i]

    // 如果当前 item 的 id 匹配 props.id，删除该项
    if (item.id === props.id) {
      item.children = [];
      TreeData.value.splice(i, 1); // 删除该项
      i--; // 调整索引，因为数组长度减少了
      continue; // 继续检查下一项
    }

    // 如果 item 有 children，递归检查并删除匹配的子项
    if (item.children && item.children.length > 0) {
      removeItemById(item.children, props.id);
    }
  }
}

// 递归删除子项
const removeItemById = (children, id) => {
  for (let i = 0; i < children.length; i++) {
    const child = children[i];

    // 如果当前 child 的 id 匹配 id，删除该项
    if (child.id === id) {
      children.splice(i, 1); // 删除该项
      i--; // 调整索引
      continue; // 继续检查下一项
    }

    // 如果 child 有 children，递归检查
    if (child.children && child.children.length > 0) {
      removeItemById(child.children, id);
    }
  }
};

watch(
    () => props.dialogVisible,
    () => {
      let id = props.id;
      TableData.value = props.tableData;
      TreeData.value = JSON.parse(JSON.stringify(props.tableData)); //深拷贝，数据不互相影响
      if (id !== -1) {
        initFormData(id);
        initGroupTreeData();
      } else {
        form.value = {
          id: -1,
          parent_id: 0,
          name: ''
        }
      }
    }
)

const emits = defineEmits(['update:modelValue', 'initTreeData'])

const handleClose = () => {
  emits('update:modelValue', false)
}

const handleConfirm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      let res = await requestUtil.post('host/group/action', form.value);
      let data = res.data;
      if (data.code === 200) {
        ElMessage.success('执行成功')
        formRef.value.resetFields()
        emits('initTreeData')
        handleClose()
      } else {
        ElMessage.error(data.msg)
      }
    } else {
      console.log('fail')
    }
  })
}
const filteredTreeData = computed(() => {
  return TreeData.value.map(item => {
    // 如果当前项有子项且子项还有子项（即有孙子项）
    if (item.children && item.children.length > 0) {
      const target = props.tableData.find(item => item.id === props.id);
      // 检查children是否有值
      if (target?.children && target?.children?.length > 0) {
        return {
          ...item,
          children: [] // 清空子项
        }
      } else {
        const newItem = {...item};
        newItem.children = newItem.children.map(child => {
          // 如果子项有子项（孙子项），则移除孙子项
          if (child.children && child.children.length > 0) {
            return {
              ...child,
              children: [] // 清空孙子项
            };
          }
          return child;
        });
        return newItem;
      }
    }
    return item;
  });
});
</script>

<template>
  <el-dialog
      model-value="dialogVisible"
      :title="dialogTitle"
      style="padding: 40px"
      width="500px"
      @close="handleClose"
      :close-on-click-modal="false"
  >
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
    >
      <el-form-item label="上级分组" prop="parent_id">
        <el-select v-model="form.parent_id" placeholder="请选择上级分组">
          <el-option label='顶级' :value="0"></el-option>
          <template v-for="item in filteredTreeData" :key="item.id">
            <el-option :label="item.name" :value="item.id"></el-option>
            <template v-for="child in item.children" :key="child.id">
              <el-option :label="child.name" :value="child.id">
                <span>&nbsp;&nbsp;&nbsp;&nbsp;{{ '- ' + child.name }}</span>
              </el-option>
            </template>
          </template>
        </el-select>
      </el-form-item>

      <el-form-item label="分组名称" prop="name">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">确认</el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">

</style>